<template>
  <div class="audition170">
    <p>方法一：</p>
    <v-md-preview :text="text1" />
    <p>方法二：利用Promise.race, const p = Promise.race([p1, p2, p3])，p也是一个promise，p的resolve或reject结果就是p1 p2 p3中最先resolve或reject的结果</p>
    <v-md-preview :text="text2" />
    <p>以上两种方法，推荐阅读：<a href="https://blog.csdn.net/zz_jesse/article/details/113154610" target="_blank">取消promise</a></p>
    <p>axios中取消请求</p>
    <v-md-preview :text="text3" />
    <p>推荐阅读：<a href="https://www.cnblogs.com/ysk123/p/11544211.html" target="_blank">axios之cancelToken</a></p>
  </div>
</template>

<script>
const prefix = '``` js'
const suffix = '```'
export default {
  name: 'Audition170',
  data() {
    return {
      text1: `${prefix}
      function getPromise(cb) {
        let _resolve, _reject
        const p = new Promise((resolve, reject) => {
          _resolve = resolve
          _reject = reject
          cb && cb(_resolve, _reject)
        })
        return {
          p,
          abort() {
            _reject('promise被阻止了')
          }
        }
      }
      function _cb(resolve, reject) {
        setTimeout(() => {
          resolve(233)
        }, 1000)
      }
      const {p, abort} = getPromise(_cb)
      p
      .then(data => console.log(data))
      .catch(err => console.log(err))
      // 调用阻止函数
      abort()
      \n${suffix}`,
      text2: `${prefix}
      // 传入一个正在执行的promise
      function getPromise(p) {
        let obj = {}
        const p1 = new Promise((resolve, reject) => {
          obj.abort = reject
        })
        obj.promise = Promise.race([p, p1])
        return obj
      }
      // 测试
      var p = new Promise(resolve => {
        setTimeout(() => {
          resolve(111)
        }, 3000)
      })
      const {promise, abort} = getPromise(p)
      // 执行
      promise
      .then(data => console.log(data))
      .catch(err => console.log(err))
      // 阻止
      abort('取消执行')
      \n${suffix}`,
      text3: `${prefix}
      var CancelToken = axios.CancelToken;
      var source = CancelToken.source();
      axios.get('/user/12345', {//get请求在第二个参数
        cancelToken: source.token
      }).catch(function(thrown) {
      });
      axios.post('/user/12345', {//post请求在第三个参数
        name: 'new name'
      }, {
        cancelToken: source.token
      });
      source.cancel('不想请求了');
      \n${suffix}`,
    }
  }
}
</script>

<style>

</style>